package Server;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPServer extends Thread{

	String serverName;
	int portNo; // ports = {6789,6790,6791}; spvm, spl, spb
	StationServer ss;
	StationServerImpl ssImpl;
	
	// default constructor
	public UDPServer() throws SocketException {
	}
	
	public UDPServer(String serverName, int portNo, StationServerImpl ssImpl) throws SocketException {
	
		this.serverName = serverName;
		this.portNo = portNo;
		this.ssImpl=ssImpl;
		
	//	 System.out.println("IN UDP Constructor: serverName: "+ serverName+ " portNo : "+ portNo + /*"  ss : "+stationServer +*/ " has started running!");
	} // end of parameterized UDPClient constructor
	
	public void run()
	{
		System.out.println("IN UDP SERVER run() : serverName: "+ serverName + " portNo : "+ portNo + " is running!");
		
		DatagramSocket aSocket =null;
		
	try{

		byte [] receivedData = new byte[55]; // received data from other servers
		byte [] dataToSend = new byte[55]; // data sent to other servers
		aSocket = new DatagramSocket(this.portNo);
		while(true){
			
			DatagramPacket request = new DatagramPacket(receivedData,receivedData.length);
			
			aSocket.receive(request);
						
			String c=ssImpl.getTotalCountFromMyServer(this.serverName,this.portNo); 
			System.out.println(c);
			
			dataToSend=c.getBytes();
			DatagramPacket reply= new DatagramPacket(dataToSend,dataToSend.length,request.getAddress(),request.getPort());
			aSocket.send(reply);
			
			} // end of while(true)
		
	}// end of try block
	catch(Exception e)
	{
		aSocket.close();
	}
	
	finally{
		if(aSocket!= null ){
			
			aSocket.close();
	} // end of if block
	} // end of finally block 	

	}// end of run method of Thread class
}// end of class UDPClient